package top.alanshelby.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.alanshelby.entity.Item;
import top.alanshelby.service.ItemService;
import top.alanshelby.vo.ItemQueryVO;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "param")
public class BindParamController {

    @Autowired
    private ItemService itemService;

    /**
     * 非注解简单参数绑定
     */
    @RequestMapping(value = "getItem")
    public Item getItem(Integer id) {
        Item item = itemService.getItemById(id);
        return item;
    }

    /**
     * 注解参数简单参数绑定
     * 此处的@RequestParam注解相当于request.getParameter(请求参数key)
     */
    @RequestMapping(value = "getItem1")
    public Item getItem1(@RequestParam(value = "itemId", required = false, defaultValue = "2") Integer id) {
        Item item = itemService.getItemById(id);
        return item;
    }

    /**
     * 绑定POJO类型
     * ?id=3&name=小米&price=3760
     */
    @RequestMapping(value = "bindPojo")
    public Item bindPojo(Item item) {
        return item;
    }

    /**
     * 绑定VO类型
     * ?item.id=4&item.name=魅族Pro5&item.price=3160&remarks=很多年前的手机型号，现在还在用
     */
    @RequestMapping(value = "bindVO")
    public ItemQueryVO bindPojo(ItemQueryVO vo) {
        return vo;
    }

    /**
     * 使用简单类型数组接收参数
     * ?ids=1&ids=2&ids=3&ids=4
     */
    @RequestMapping(value = "simpleArray")
    public String[] simpleArray(String[] ids) {
        return ids;
    }

    /**
     * 用POJO类型集合或者数组接收参数
     * ?itemList[0].id=1&itemList[0].name=iphone&itemList[0].price=6000&itemList[1].id=2&itemList[1].name=iphone x&itemList[1].price=9000
     */
    @RequestMapping(value = "bindBatchParam")
    public List<Item> bindBatchParam(ItemQueryVO vo) {
        return vo.getItemList();
    }

    /**
     * 自定义参数绑定
     */
    @RequestMapping(value = "dateParam")
    public Date bindBatchParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date) {
        return date;
    }
}
